using System;
using System.Collections.Generic;
using System.Text;
using AandEDLL.DataAccess;

namespace AandEDLL.ItemSearchAPI
{
    class EbaySearchService : SearchService
    {
        public override void initializeService()
        {
        }
        public override List<Item> search(String criterion)
        {
            List<Item> searchResults = new List<Item>();
            String endpoint = "https://api.ebay.com/wsapi";
            String callName = "GetSearchResults";
            String siteId = "0";
            //Test
            //String appId = "WSUP4V15SGEP615BW21SR8Z5ELKY8N";
            //String certId = "K2G1W31XQ6R$3SM71H522-5U175911";
            //String devId = "V33LR6XC43G565T422DSGIX8G8IIEN";
            //Prod
            String appId = "WSUX1RB3J9JI6L56K11LA34I851361";
            String certId = "P711F4M5DH9$9Q6I41766-Q751CS14";
            String devId = "V33LR6XC43G565T422DSGIX8G8IIEN";
            String version = "405";
            string requestURL = endpoint
                    + "?callname=" + callName
                    + "&siteid=" + siteId
                    + "&appid=" + appId
                    + "&version=" + version
                    + "&routing=default";
            // Create the service 
            eBayAPIInterfaceService service = new eBayAPIInterfaceService();
            // Assign the request URL to the service locator. 
            service.Url = requestURL;
            // Set credentials 
            service.RequesterCredentials = new CustomSecurityHeaderType();
            //Test
            //service.RequesterCredentials.eBayAuthToken = "AgAAAA**AQAAAA**aAAAAA**gQzMRQ**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wFk4CnCZOGogqdj6x9nY+seQ**yqEAAA**AAMAAA**pjGqrr/4u3lJIe1iHbMNn5qvHF/ILtVkgqMcCRGK6jP+OyVELx24w4owKiBbwoGwbC70o9b5eksyjHfXm4rHCKfIi2UOwlGVTQytKxSfpJkD/wZc2l03y9cRxTLm4cS4De7SsURc3DaE6aQt2ibGcv4UT7X2TA8gIkv02/HjS6srYSgEcxyxVdng5wkISO8DgzUHORtikdvKuSGddiFV1AMgV4sqnG4nHRHDVmeMVXXVsPevQMeZ+VjFxF4MbbvwLLjEafZgGi8xQQ0biDob/ZSUkEJGoFOs633+7yQuy/835CPYlMSBuI7NE1x0rtTd3q+qJl2n+vnrUYRoa5uzmfqF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R0QyEGiAH5WMfkI2rItYy3oVDJEn70bFV8Tu3asz5HrJ0S1n+Hs8ildLfxbYI5iS+kVeejfQU+l6xrkqC5jzbtYvJPdgReaUh+Qunzosv0mHB9vg8rKROGBK1L0mNVE+evkyHVsE2WPOJuvl5VZs0yiYVnE+bvUOWaXNGWDhOq2kF+oMZzXSY41Jod1gMuxuyzkqPup7PWD9A8B3xBEGAwA7YnNZCCwFoLTUemvpNNdNVI3pOyo3T+g30rQMUNE";
            service.RequesterCredentials.Credentials = new UserIdPasswordType();
            service.RequesterCredentials.Credentials.AppId = appId;
            service.RequesterCredentials.Credentials.DevId = devId;
            service.RequesterCredentials.Credentials.AuthCert = certId;

            GetSearchResultsRequestType theRequest = new GetSearchResultsRequestType();
            theRequest.Version = version; // Payload version 
            theRequest.ErrorLanguage = "en"; // Language for error messages 

            theRequest.Query = criterion;

            // Set pagination to retrieve 50 items in the call 
            PaginationType p = new PaginationType();
            p.EntriesPerPage = 50;
            p.PageNumber = 1;
            theRequest.Pagination = p;

            // Declare the response object (theResponse) 
            GetSearchResultsResponseType theResponse = null;
            // Make the call 
            // Always use error trapping to ensure API calls are safely made 
            try
            {
                // Create the response object with data from eBay service execution method 
                theResponse = service.GetSearchResults(theRequest);
                if (theResponse.PaginationResult.TotalNumberOfEntries > 0)
                {
                    for (int x = 0; x < theResponse.SearchResultItemArray.Length; x++)
                    {
                        if (theResponse.SearchResultItemArray[x].Item.BuyItNowPrice == null && 
                            theResponse.SearchResultItemArray[x].Item.SellingStatus.CurrentPrice == null)
                            continue;
                        //if (theResponse.SearchResultItemArray[x].Item.BuyItNowPrice.Value > 0)
                        //{
                            Item item = new Item();
                            String name = theResponse.SearchResultItemArray[x].Item.Title;
                            String desc = theResponse.SearchResultItemArray[x].Item.Description;                            

                            item.ItemName = name;
                            item.Description = desc;
                            if (theResponse.SearchResultItemArray[x].Item.BuyItNowPrice != null)
                                item.Price = Convert.ToDecimal(theResponse.SearchResultItemArray[x].Item.BuyItNowPrice.Value);
                            else
                            {
                                try
                                {
                                    item.Price = Convert.ToDecimal(theResponse.SearchResultItemArray[x].Item.SellingStatus.CurrentPrice.Value);
                                }
                                catch
                                {
                                    throw new Exception("Cannot Convert " + theResponse.SearchResultItemArray[x].Item.SellingStatus.CurrentPrice.Value);
                                }
                            }
                            
                            item.SearchDate = DateTime.Now;
                            item.URL = theResponse.SearchResultItemArray[x].Item.ListingDetails.ViewItemURL; 
                            //item.URL = "http://www.ebay.com";
                            item.Source = "EBAY";
                            searchResults.Add(item);
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.StackTrace);
            }
            return searchResults;
        }
    }
}
